package com.reservation.utils;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
/**
 * URL工具类，用于构建资源的完整URL
 */
@Component
public class UrlUtil {

    /**
     * 构建完整的资源URL
     * @param relativePath 资源的相对路径
     * @return 完整的URL
     */
    public static String buildFullUrl(String relativePath) {
        if (relativePath == null || relativePath.isEmpty()) {
            return null;
        }

        // 获取当前请求
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return relativePath; // 如果无法获取请求，则直接返回相对路径
        }

        HttpServletRequest request = attributes.getRequest();

        // 构建基础URL
        String scheme = request.getScheme();
        String serverName = request.getServerName();
        int serverPort = request.getServerPort();

        StringBuilder baseUrl = new StringBuilder();
        baseUrl.append(scheme).append("://").append(serverName);
        if (serverPort != 80 && serverPort != 443) {
            baseUrl.append(":").append(serverPort);
        }

        // 相对路径已包含前导斜杠
        return baseUrl.toString() + relativePath;
    }
}
